
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;


/**
 *
 * @author Zuzana Krejcova
 */
public class Configuration
{
    private File config;
    Document doc;

    public Configuration() throws ParserConfigurationException, SAXException, IOException
    {
        config = new File(System.getProperty("user.home")+File.separator+".transformator_gramatik.conf");
        DocumentBuilderFactory factoryDom = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factoryDom.newDocumentBuilder();
        if (!config.exists()) setNewFile();
        doc = builder.parse(config.getPath());
    }

    public String getItemConfig(JButton butt)
    {
        return doc.getElementsByTagName(butt.getName()).item(0).getTextContent();
    }

    public void saveConfiguration()
    {
        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(config);
            transformer.transform(source, result);
        } catch (Exception e) {}
    }

    public void setItem(JButton butt)
    {
        doc.getElementsByTagName(butt.getName()).item(0).setTextContent(butt.getText());
    }

    private void setNewFile() throws IOException
    {
        BufferedWriter configOut = new BufferedWriter(new FileWriter(config));
        configOut.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ 
                        "<conf>\n<fav1>nic</fav1>\n<fav2>nic</fav2>\n<fav3>nic</fav3>\n"+
                        "</conf>");
        configOut.close();
    }
}
